package com.lyb.util;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

import com.lyb.app.App;
import com.lyb.bean.UserSmsInfoBean;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Description:
 * Author     : Xiccc.
 * Date       : 2017/11/29 16:37
 */

public class SmsUtil {

    /**
     * 获取短信记录
     */
    public static List<UserSmsInfoBean> getSmsInfoList(Context context) {

        List<UserSmsInfoBean> list = new ArrayList<>();
        Uri SMS_INBOX = Uri.parse("content://sms/");
        ContentResolver cr = context.getContentResolver();
        String[] projection = new String[]{"_id", "address", "person", "body", "date", "type"};
        //String where = "date>" + (System.currentTimeMillis() - 15552000000l);//30天 = 30*24*60*60*1000ms = 2592000000ms
        Cursor cur = cr.query(SMS_INBOX, projection, null, null, "date desc");
        if (cur != null && cur.moveToFirst()) {
            LogUtils.loge("cur" + cur.getColumnCount());
            int phoneNumberColumn = cur.getColumnIndex("address");
            int dateColumn = cur.getColumnIndex("date");
            int bodyColumn = cur.getColumnIndex("body");
            do {
                String phoneNumber;
                String date;
                String body;
                phoneNumber = cur.getString(phoneNumberColumn);
                body = cur.getString(bodyColumn);
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date d = new Date(Long.parseLong(cur.getString(dateColumn)));
                date = dateFormat.format(d);
                UserSmsInfoBean mUserSmsInfo = new UserSmsInfoBean();
                mUserSmsInfo.setMessageContent(body);
                mUserSmsInfo.setMessageDate(date);
                mUserSmsInfo.setPhone(phoneNumber);
                if (App.getConfig().getUserInfo() != null) {
                    mUserSmsInfo.setUserId(App.getConfig().getUserInfo().getUid());
                }
                LogUtils.loge("输出手机中的 number=" + "--内容body=" + body + "--data=" + date + "--phoneNumber=" +
                        phoneNumber);
                if (list.size() < 1000) {
                    list.add(mUserSmsInfo);
                } else {
                    cur.moveToLast();
                }

            } while (cur.moveToNext());
            if (!cur.isClosed()) {
                cur.close();
            }
        }
        return list;
    }
}
